export function flexible () {
  const docEl = document.documentElement;

  // set 1rem = viewWidth / 10
  function setRemUnit () {
    const width = docEl.clientWidth > 640 ? 640 : docEl.clientWidth;
    const rem = width / 10;
    docEl.style.fontSize = rem + 'px';
  }
  setRemUnit();
  // reset rem unit on page resize
  window.addEventListener('resize', setRemUnit);
}

// 处理ios微信下键盘收起页面未归位bug
export function fixIosInputBlur (e) {
  if (isIos()) {
    ['input', 'textarea'].includes(e.target.localName) && document.body.scrollIntoView(false);
  }
}

export function getPlantform (userAgent = navigator.userAgent) {
  if (/Android|iPhone|iPad|iPod|Windows Phone|BlackBerry/i.test(userAgent)) {
    return 'mobile';
  } else {
    return 'pc';
  }
}

export function isIos () {
  if (/iPad|iPhone|iPod/i.test(navigator.userAgent)) {
    return true;
  } else {
    return false;
  }
}

export function isAndroid () {
  if (/Android/i.test(navigator.userAgent)) {
    return true;
  } else {
    return false;
  }
}

export function isWechat () {
  return /microMessenger/i.test(navigator.userAgent);
}

export function shouldSetTitle () {
  return /microMessenger|QQ/i.test(navigator.userAgent);
}

export function isQQBrowser () {
  return /MQQBrowser/i.test(navigator.userAgent);
}

export function isNativeApp () {
  return /u-android|u-ios|haibao-ios|haibao-android/i.test(navigator.userAgent);
}

export function isNativeIos () {
  return /u-ios|haibao-ios/i.test(navigator.userAgent);
}

export function isNativeAndroid () {
  return /u-android|haibao-android/i.test(navigator.userAgent);
}

export function isPC () {
  return getPlantform() == 'pc';
}

export function isMobile () {
  return getPlantform() == 'mobile';
}

export function setTitle (title) {
  if (shouldSetTitle()) {
    document.title = title;
    let i = document.createElement('iframe');
    i.src = '//oss.baobaobooks.net/favicon.ico';
    i.style.display = 'none';
    i.onload = function () {
      setTimeout(function () {
        i.remove();
      }, 9);
    };
    document.body.appendChild(i);
  } else {
    document.title = title;
  }
}

export function isSupportWebp () {
  return new Promise((resolve, reject) => {
    const image = new Image();
    image.onerror = () => {
      reject(false);
    };
    image.onload = () => {
      resolve();
    };
    image.src = 'data:image/webpbase64,UklGRiwAAABXRUJQVlA4ICAAAAAUAgCdASoBAAEAL/3+/3+CAB/AAAFzrNsAAP5QAAAAAA==';
  });
}

// export function setSupportWebp () {
//   if (cookies.get('supportWebp') == '1') return;
//   isSupportWebp()
//     .then(() => {
//       cookies.set('supportWebp', 1, { expires: 3650, domain: getRootDomain() });
//     })
//     .catch(() => {
//       cookies.set('supportWebp', 0, { expires: 3650, domain: getRootDomain() });
//     });
// }

let scrollTimer;

export function scrollTop (position, duration) {
  let n = Math.max(parseInt(document.getElementsByTagName('html')[0].scrollTop), parseInt(document.getElementsByTagName('body')[0].scrollTop));
  let o = 0;
  let l = 10;
  position = parseInt(position);
  duration /= l;
  let a = (position - n) / duration;
  scrollTimer = setInterval(() => {
    o++;
    window.scrollTo(0, a * o + n);
    if (o >= duration) {
      clearInterval(scrollTimer);
    }
  }, l);
}

export function getParameterByName (name, url) {
  if (!url) url = window.location.href;
  name = name.replace(/[\[\]]/g, '\\$&');
  const regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
    results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, ''));
}

// export function scrollTo (element, to, duration) {
//   if (duration <= 0) return
//   var difference = to - element.scrollTop
//   setTimeout(() => {
//     element.scrollTop = element.scrollTop + perTick
//     if (element.scrollTop === to) return
//     scrollTo(element, to, duration - 10)
//   }, 10)
// }

function hasVariableHandle (variable, resolve) {
  if (window[variable]) {
    resolve();
    return true;
  }
}

function hasVariableTimer (variable, resolve) {
  setTimeout(() => {
    if (hasVariableHandle(variable, resolve)) return;
    hasVariableTimer(variable, resolve);
  }, 10);
}

export function hasVariable (variable) {
  return new Promise(resolve => {
    if (!hasVariableHandle(variable, resolve)) {
      hasVariableTimer(variable, resolve);
    }
  });
}

export let supportsPassive = false;

export function testSupportsPassive () {
  const opts = Object.defineProperty({}, 'passive', {
    get: function () {
      supportsPassive = true;
    }
  });
  window.addEventListener('testPassive', null, opts);
  window.removeEventListener('testPassive', null, opts);
}

export function freeze (lock = true) {
  if (lock) {
    if (isPC()) {
      const scrollWidth = getScrollbarWidth();
      document.documentElement.style.paddingRight = `${scrollWidth}px`;
      handleFixedElement(scrollWidth);
    }
    document.body.classList.add('overflow');
    if (supportsPassive) {
      window.addEventListener('touchstart', startMove, { passive: false });
      window.addEventListener('touchmove', disableMove, { passive: false });
    } else {
      window.addEventListener('touchstart', startMove);
      window.addEventListener('touchmove', disableMove);
    }
  } else {
    if (isPC()) {
      document.documentElement.style.paddingRight = '0';
      handleFixedElementRemove();
    }
    document.body.classList.remove('overflow');
    window.removeEventListener('touchmove', disableMove);
  }
}

export function unFreezeScroll () {
  window.removeEventListener('touchmove', disableMove);
}

export function freezeChild (freeze = true) {
  if (isMobile()) return;
  if (freeze) {
    const scrollWidth = getScrollbarWidth();
    handleFixedElement(scrollWidth);
  } else {
    handleFixedElementRemove();
  }
}

function handleFixedElement (scrollWidth) {
  setTimeout(() => {
    const eles = document.querySelectorAll('.fixed-width');
    for (let item of eles) {
      if (item.classList.contains('fixed-width2')) {
        item.style.marginLeft = `${-320 - scrollWidth / 2}px`;
      } else {
        item.style.transform = `translateX(-${scrollWidth / 2}px)`;
      }
    }
  });
}

function handleFixedElementRemove () {
  const eles = document.querySelectorAll('.fixed-width');
  for (let item of eles) {
    if (item.classList.contains('fixed-width2')) {
      item.style.marginLeft = `-320px`;
    } else {
      item.style.transform = `translateX(0)`;
    }
  }
}

let startMoveYmap = {};

function startMove (e) {
  const ele = e.target.closest('.scroll-enable');
  if (ele) {
    startMoveYmap[ele.id] = e.touches[0].clientY;
  }
}

function disableMove (e) {
  const ele = e.target.closest('.scroll-enable');
  if (!ele) {
    e.preventDefault();
    return;
  }

  // 高位表示向上滚动, 底位表示向下滚动: 1容许 0禁止
  let status = '11';
  let currentY = e.touches[0].clientY;
  let startY = startMoveYmap[ele.id];
  let scrollTop = ele.scrollTop;
  let offsetHeight = ele.offsetHeight;
  let scrollHeight = ele.scrollHeight;

  if (scrollTop === 0) {
    // 如果内容小于容器则同时禁止上下滚动
    status = offsetHeight >= scrollHeight ? '00' : '01';
  } else if (scrollTop + offsetHeight >= scrollHeight) {
    // 已经滚到底部了只能向上滚动
    status = '10';
  }

  if (status != '11') {
    // 判断当前的滚动方向
    let direction = currentY - startY > 0 ? '10' : '01';

    // 操作方向和当前允许状态求与运算，运算结果为0，就说明不允许该方向滚动，则禁止默认事件，阻止滚动
    if (!(parseInt(status, 2) & parseInt(direction, 2))) {
      e.preventDefault();
      e.stopPropagation();
    }
  }
}

export function getScrollbarWidth () {
  if (document.body.scrollHeight <= document.body.clientHeight) {
    return 0;
  }
  let outer = document.createElement('div');
  outer.style.visibility = 'hidden';
  outer.style.width = '100px';
  outer.style.msOverflowStyle = 'scrollbar'; // needed for WinJS apps

  document.body.appendChild(outer);

  let widthNoScroll = outer.offsetWidth;
  // force scrollbars
  outer.style.overflow = 'scroll';

  // add innerdiv
  let inner = document.createElement('div');
  inner.style.width = '100%';
  outer.appendChild(inner);

  let widthWithScroll = inner.offsetWidth;

  // remove divs
  outer.parentNode.removeChild(outer);

  return widthNoScroll - widthWithScroll;
}

export function countdownTime (distance, htmlTag = false, activityTag = false, topicObj = {
  topicTag: false,
  isStart: false,
  isEnded: false,
  showText: false
}) {
  let days = Math.floor(distance / (1000 * 60 * 60 * 24));
  let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  let seconds = Math.floor((distance % (1000 * 60)) / 1000);
  if (htmlTag) {
    let result = !days ? '' : `${handleZero(days)}<span>天</span>`;
    return `${result}${handleZero(hours)}<span>时</span>${handleZero(minutes)}<span>分</span>${handleZero(seconds)}<span>秒</span>`;
  }
  if (activityTag) {
    return `距开抢剩 <span>${handleZero(hours)}</span> : <span>${handleZero(minutes)}</span> : <span>${handleZero(seconds)}</span>`;
  }
  if (topicObj.topicTag) {
    let totalHours = !days ? `${handleZero(hours)}` : `${24 * days + hours}`;
    if (!topicObj.isStart) {
      return `距离开抢还剩 <span class='time-text'>${totalHours}:${handleZero(minutes)}:${handleZero(seconds)}</span>`;
    } else {
      if (!topicObj.isEnded) {
        if (!topicObj.showText) {
          return '<p class=\'time-text\'>狂抢中...</p>';
        }
        return '';
      }
    }
  }
  let result = !days ? '' : `${handleZero(days)}天`;
  return `${result}${handleZero(hours)}时${handleZero(minutes)}分${handleZero(seconds)}秒`;
}

export function handleZero (number) {
  if (String(number).length == 1) {
    return '0' + number;
  }
  return number;
}

export function loadScript (src, variable) {
  if (variable && window[variable]) {
    return Promise.resolve();
  }
  return new Promise(resolve => {
    const ele = document.createElement('script');
    ele.src = src;
    document.getElementsByTagName('head')[0].appendChild(ele);
    // 兼容ie10
    ele.onload = ele.onreadystatechange = function() {
      if (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') {
        resolve();
      }
    };
  });
}

export function loadStyle (src) {
  return new Promise(resolve => {
    const ele = document.createElement('link');
    ele.href = src;
    ele.type = 'text/css';
    ele.rel = 'stylesheet';
    document.getElementsByTagName('head')[0].appendChild(ele);
    ele.onload = function() {
      resolve();
    };
  });
}

export function stringToOppNumber (text) {
  if (text == '1') {
    return '0';
  } else {
    return '1';
  }
}

export function openQQ (qq) {
  window.open(`http://wpa.b.qq.com/cgi/wpa.php?ln=2&uin=${qq}`);
}

export function handleUrl (url, router) {
  if (url.indexOf('http') === 0) {
    location.href = url;
    return;
  }
  router.push(url);
}

export let cachedImage = new Set();

export function isMobileNumber (number, countryCode = '86') {
  if (countryCode == '86') {
    return /^1\d{10}$/.test(number);
  }
  return number.length > 5;
}

export function isMobileNum (val) {
  return /^1(3|4|5|7|8)\d{9}$/.test(val);
}

export function isCode (val) {
  return /^\d{6}$/.test(val);
}

export function isPurchaseDomain () {
  return location.hostname.split('.')[0] == 'b';
}

function hasElementHandle (query, resolve) {
  const ele = document.querySelector(query);
  if (ele) {
    resolve(ele);
    return true;
  }
}

function hasElementTimer (query, resolve) {
  setTimeout(() => {
    if (hasElementHandle(query, resolve)) return;
    hasElementTimer(query, resolve);
  }, 400);
}

export function hasElement (query) {
  return new Promise(resolve => {
    if (!hasElementHandle(query, resolve)) {
      hasElementTimer(query, resolve);
    }
  });
}

export function scrollViewKeyboard (e) {
  if (isPC()) {
    return;
  }
  setTimeout(() => {
    window.isFocus = true;
    let pannel = e.target;
    pannel.scrollIntoView(true);
    pannel.scrollIntoViewIfNeeded();
  }, 200);
}

export function restorePopUpKeyboard (scrollTop = 0) {
  if (!isMobile()) {
    return;
  }
  window.isFocus = false;
  setTimeout(() => {
    if (window.isFocus) {
      window.isFocus = false;
      return;
    }
    const bodyScrollTop = document.body.scrollTop;
    setScrollTop(bodyScrollTop - scrollTop);
  }, 300);
}

export function getScrollOffsetBottom () {
  const pageHeight = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
  const scrollTop = Math.max(document.body.scrollTop, document.documentElement.scrollTop);
  return pageHeight - document.body.offsetHeight - scrollTop;
}

export function currencyToNumber (string) {
  return Number(string.slice(1));
}

export function setDesc (desc) {
  const tages = document.getElementsByTagName('meta');
  const tag = Array.from(tages).find(item => {
    return item.name == 'description';
  });
  if (tag) {
    tag.setAttribute('content', desc);
  }
}

export function setScrollTop (number) {
  document.body.scrollTop = number;
  document.documentElement.scrollTop = number;
}

export function shouldOpenBrowser () {
  return /microMessenger|QQ|Weibo/i.test(navigator.userAgent);
}

export function isOpenApp () {
  return location.hostname.indexOf('oia') != -1;
}

export function getBrowser () {
  if (/iPad|iPhone|iPod/.test(navigator.userAgent)) {
    return 'Safari';
  }
  return '浏览器';
}

function addZero (m) {
  return m < 10 ? '0' + m : m;
}

export function formatTime (timeStamp, char) {
  //timeStamp，否则要parseInt转换
  var time = new Date(timeStamp * 1000);
  var y = time.getFullYear();
  var m = time.getMonth() + 1;
  var d = time.getDate();
  var h = time.getHours();
  var mm = time.getMinutes();
  var s = time.getSeconds();
  return y + char + addZero(m) + char + addZero(d) + ''  + addZero(h) + ':' + addZero(mm) + ':' + addZero(s);
}

export function timestampToTime (timestamp, char) {
  var date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
  var Y = date.getFullYear() + char;
  var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + char;
  var D = date.getDate();
  return Y + M + D;
}

export async function initSwiper (container = '#swiper-top-container', options) {
  await loadScript('//static.baobaobooks.net/misc/swiper/swiper.min.js', 'Swiper');
  let defaultOptions = {
    pagination: '.swiper-pagination',
    paginationClickable: true,
    preloadImages: false,
    lazyLoading: true,
    lazyLoadingInPrevNext: true,
    loop: true,
    spaceBetween: 12,
    autoplay: 5000
  };
  hasVariable('Swiper').then(() => {
    new Swiper(container, Object.assign(defaultOptions, options));
  });
}
export function setStoreCookie (cookieName) {
  cookies.set(cookieName, 1, {
    // 1小时过期
    expires: 1 / 24 / 2,
    domain: getRootDomain()
  });
}
export default {};
